﻿var todoObj = {};

todoObj.getTodoItems = function () {
    var request = new XMLHttpRequest();
    request.open('GET', '/api/apiTodo/');
    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            var data = JSON.parse(this.response);

            todoObj.displayTable(data);
        }
    };

    request.send();
};

todoObj.displayTable = function (data) {
    var h = '<table class="table table-bordered table-striped">';
    h += '<tr>';
    h += '<td>Task Name</td>';
    h += '<td>Timestamp</td>';
    h += '<td>Completed</td>';
    h += '</tr>';

    for (var t in data) {
        h += '<tr>';
        h += '<td>' + data[t].taskName + '</td>';
        h += '<td>' + data[t].timestamp + '</td>';
        h += data[t].isCompleted ? '<td>' + data[t].dateCompleted + '</td>' : '<td>Incomplete</td>';
        h += '</tr>';
    }

    h += '</table>';

    document.getElementById('output').innerHTML = h;
};

todoObj.createTodoItem = function () {
    var taskInput = document.getElementById('taskName');

    var request = new XMLHttpRequest();
    request.open('POST', '/api/apiTodo/');
    request.setRequestHeader("Content-Type", "application/json");
    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            todoObj.getTodoItems();
            taskInput.value = "";
        }
    };

    var newTodo = {
        taskName: taskInput.value
    };

    request.send(JSON.stringify(newTodo));
};

todoObj.getTodoItems();